<template>
	<div class="relative z-20" ref="selectModel">
		<div
			class="w-full px-2 h-10 bg-slate-200 rounded-lg border border-slate-300 hover:border-[#6B5CFF] flex justify-between items-center"
			@click="showDropdown = !showDropdown"
		>
			<div class="flex items-center">
				<img :src="showModel.icon" class="w-5 h-5 mr-2" />
				<span class="text-[12px]">{{ showModel.name }}</span>
			</div>
			<i
				class="iconfont icon-arrow-down-s-line transition-transform duration-300 ease-in-out"
				:class="{ 'rotate-180': showDropdown }"
			></i>
		</div>

		<div
			v-show="showDropdown"
			class="hidden md:block w-full p-4 absolute top-12 bg-white rounded-2xl max-h-[410px] overflow-y-auto scrollable"
		>
			<div
				v-for="item in options"
				:key="item.name"
				class="py-2 mb-2 cursor-pointer duration-500 hover:bg-slate-100 p-2 rounded-lg flex items-center justify-between"
				:class="{ 'bg-slate-100': item.children?.[0].id === selectedModel }"
				@click="handleSelectModel(item)"
				@mouseenter="handleMouseEnter(item)"
			>
				<DefineTemplate #default="{ item }">
					<div class="flex flex-col gap-1 w-full">
						<div class="flex items-center gap-2">
							<img
								:src="item.children?.[0].icon ?? item.icon"
								class="w-5 h-5"
							/>
							<span class="text-[12px]">{{ item.name }}</span>

							<img
								v-show="hasSub(item) ? item.children?.[0].is_new : item.is_new"
								src="https://vapps-res.media.io/mediaai/app_static/new.png"
								class="h-5 object-contain"
							/>

							<img
								v-show="
									hasSub(item)
										? !item.children?.[0].is_new && item.children?.[0].is_hot
										: !item.is_new && item.is_hot
								"
								src="https://vapps-res.media.io/mediaai/app_static/hot.png"
								class="h-5 object-contain"
							/>
						</div>
						<div class="text-[12px] text-slate-400">
							{{ item.description }}
						</div>
						<div class="flex gap-2">
							<div
								v-for="tag in (hasSub(item)
									? item.children?.[0]?.label?.split('|')
									: item.label?.split('|')) || []"
								class="px-2 py-1 border border-slate-300 rounded-md text-[12px] text-slate-500"
							>
								{{ tag }}
							</div>
						</div>
					</div>

					<i v-show="hasSub(item)" class="iconfont icon-arrow-right-s-line"></i>
					<i
						v-show="item.id === selectedModel"
						class="iconfont icon-duigou"
					></i>
					<i
						v-show="!hasSub(item) && item.children?.[0].id === selectedModel"
						class="iconfont icon-duigou"
					></i>
				</DefineTemplate>

				<ReuseTemplate :item />
			</div>
		</div>

		<div
			v-show="showSubDropdown"
			class="hidden md:block w-full p-4 absolute left-[102%] top-12 bg-white rounded-2xl max-h-[410px] overflow-y-auto scrollable"
		>
			<div
				v-for="item in hoveredParent?.children ?? []"
				@click="handleSelectModel(item)"
				class="py-2 mb-2 cursor-pointer duration-500 hover:bg-slate-100 p-2 rounded-lg flex items-center justify-between"
				:class="{ 'bg-slate-100': item.id === selectedModel }"
			>
				<ReuseTemplate :item />
			</div>
		</div>
	</div>

	<div class="text-sm md:hidden">
		<el-drawer
			v-model="showDropdown"
			direction="btt"
			size="550"
			class="custom-drawer"
			title="模型列表"
		>
			<div
				v-for="item in options"
				:key="item.name"
				class="py-2 mb-2 cursor-pointer duration-500 hover:bg-slate-100 p-2 rounded-lg flex items-center justify-between"
				:class="{ 'bg-slate-100': item.children?.[0].id === selectedModel }"
				@click="
					() => {
						handleSelectModel(item), handleMouseEnter(item)
					}
				"
			>
				<ReuseTemplate :item />
			</div>
		</el-drawer>

		<el-drawer
			v-model="showSubDropdown"
			direction="btt"
			size="550"
			class="custom-drawer"
		>
			<template #header>
				<div class="flex items-center text-[16px]">
					<i
						class="iconfont icon-arrow-right-s-line rotate-180"
						style="font-size: 24px"
						@click="handleBack"
					></i>
					<div class="mx-auto">模型列表</div>
				</div>
			</template>

			<div
				v-for="item in hoveredParent?.children ?? []"
				@click="handleSelectModel(item)"
				class="py-2 mb-2 cursor-pointer duration-500 hover:bg-slate-100 p-2 rounded-lg flex items-center justify-between"
				:class="{ 'bg-slate-100': item.id === selectedModel }"
			>
				<ReuseTemplate :item />
			</div>
		</el-drawer>
	</div>
</template>

<script setup lang="ts">
// import models from '@/mock/models.json'
import { getModels } from '@/api'
import { uniqueByKey } from '@/utils'

type Model = {
	id: number
	name: string
	description: string
	group: string
	group_description: string
	label: string
	is_hot: boolean
	is_new: boolean
	cost: number
	preview: string
	icon: string
}

type Option = {
	name: string
	description: string
	children?: Model[]
}

const [DefineTemplate, ReuseTemplate] = createReusableTemplate()

const options: Ref<Option[]> = ref([])

const generateOptions = (models: Model[]) => {
	const parent = uniqueByKey(
		models.map((item) => ({
			name: item.group,
			description: item.group_description,
			children: [] as Model[],
		})),
		'name'
	)
	options.value.push(...parent)
	parent.forEach((item) => {
		models.forEach((model) => {
			if (model.group === item.name) {
				item.children.push(model)
			}
		})
	})
}
const showModel = ref({
	icon: 'https://images.media.io/media-ai/icon/icon16.png',
	name: 'Pixverse V4.5',
})

onMounted(async () => {
	const res = await getModels()

	generateOptions(res)
})

const selectedModel = defineModel()
const showDropdown = ref(false)

const showSubDropdown = ref(false)

const hoveredParent = ref<Option | null>(null)

const handleMouseEnter = (item: Option) => {
	if (!hasSub(item)) hoveredParent.value = null
	hoveredParent.value = item
	showSubDropdown.value = hasSub(item)
}

const selectModelRef = useTemplateRef<HTMLElement>('selectModel')

onClickOutside(selectModelRef, () => {
	hoveredParent.value = null
	showDropdown.value = false
	showSubDropdown.value = false
})

const hasSub = (model: Option) =>
	!!(model.children && model.children.length > 1)

const handleSelectModel = (model: any) => {
	if (hasSub(model)) return

	const targetModel = model.children?.[0] || model
	selectedModel.value = targetModel.id
	showModel.value = {
		icon: targetModel.icon,
		name: model.name,
	}

	hoveredParent.value = null
	showDropdown.value = false
	showSubDropdown.value = false
}

const handleBack = () => {
	hoveredParent.value = null
	showDropdown.value = true
	showSubDropdown.value = false
}
</script>

<style scoped lang="scss"></style>
